﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common.Util;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json.Linq;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using RestSharp;
using ThumbnailSharp;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo
{
    public partial class OrderControl : UserControl
    {

        private PddTokenService pddTokenService = new PddTokenService();

        public OrderControl()
        {
            InitializeComponent();
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dataGridView1_RowPostPaint);

        }

        private void UserControl1_Load(object sender, EventArgs e)
        {
             
        }

        public async void LoadData() 
        {
            if (this.Site != null && this.Site.DesignMode) return;

            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            OrderModel orderModel = new OrderModel();
            this.dataGridView1.Rows.Clear();
            string goodId = this.goods_id.Text.Trim();

            this.dataGridView1.DataSource = new BindingList<Order>(orderList.ToList());
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            this.dataGridView1.Rows.Clear();
            this.dataGridView1.DataSource = new BindingList<Order>(orderList.ToList());
        }
     
        private void button4_Click(object sender, EventArgs e)
        {
            //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //var tokens = DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            //foreach (var order in orderList)
            //{

            //var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            //if (token == null)
            //{
            //    this.message.AppendText("小号不存在：" + order.uid + "\r\n");
            //    continue;
            //}
            //OrderStatus orderStatus = new OrderStatus();
            //orderStatus.ts = PddApi.GetPddTime();

            //string url = "http://mobile.yangkeduo.com/proxy/api/order/" + order.orderSn + "?pdduid=" + order.uid;
            //var restclient = new RestClient(url);


            //restclient.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36";

            //var request = new RestRequest(Method.POST);
            //request.AddHeader("Content-Type", "application/json");
            //request.AddHeader("Accept", "application/json, text/javascript, */*");
            //request.AddHeader("Accept-Encoding", "gzip, deflate");
            //request.AddHeader("AccessToken", token.PDDAccessToken);
            //request.AddHeader("Host", "mobile.yangkeduo.com");
            //request.AddHeader("Referer", url);
            //request.AddHeader("Origin", "http://mobile.yangkeduo.com");

            //request.AddCookie("PDDAccessToken", token.PDDAccessToken);

            //var response = await restclient.ExecuteAsync(request);
            //if (string.IsNullOrWhiteSpace(response.Content))
            //{
            //    this.message.AppendText("订单：" + order.orderSn + "获取物流信息失败 \r\n");
            //    continue;
            //}
            //var jo = JObject.Parse(response.Content);

            //var express_infoToken = jo.SelectToken("express_info");
            //if (express_infoToken != null)
            //{
            //    order.logisticsOrderNo   = express_infoToken["tracking_number"].ToString();
            //    order.logisticsCompany   = express_infoToken["shipping_name"].ToString();
            //    var traces = express_infoToken["traces"].ToArray();
            //    if (traces != null && traces.Length > 0)
            //    {
            //        var trace = traces.FirstOrDefault();
            //        string info = trace["info"].ToString();
            //        order.logisticsInfo = info;
            //    }

            //}

            //OrderStatus orderStatus = new OrderStatus();
            //orderStatus.ts = PddApi.GetPddTime();

            //string url = "http://mobile.yangkeduo.com/proxy/api/order/" + order.orderSn + "?pdduid=" + order.uid;
            //var restclient = new RestClient(url);
            //var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            //if (token == null)
            //{
            //    this.message.AppendText("小号失效：" + order.uid + "\r\n");
            //    continue;
            //}
            //if (!string.IsNullOrWhiteSpace(order.orderState))
            //{
            //    if (order.orderState.Contains("待付款") || order.orderState.Contains("待收货") || order.orderState.Contains("待发货"))
            //    {

            //    }
            //    else
            //    {
            //        continue;
            //    }

        }

        private async void button1_Click_1(object sender, EventArgs e)
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var tokens = pddTokenService.GetAllToken();
            foreach (var order in orderList)
            {
                OrderStatus orderStatus = new OrderStatus();
                orderStatus.ts = PddApi.GetPddTime();
           
                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.message.AppendText("小号没找到：" + order.uid + "\r\n");
                    continue;
                }
                if (!string.IsNullOrWhiteSpace(order.orderState))
                {
                    if (order.orderState.Contains("待付款") || order.orderState.Contains("待收货") || order.orderState.Contains("待发货") || order.orderState.Contains("待分享") || order.orderState.Contains("待评价"))
                    {

                    }
                    else
                    {
                        continue;
                    }
                }
 

                bool status =  await PddApi.GetOrderStatus(order, token);
                if (status)
                {
                    await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                }
                else 
                {
                    this.message.AppendText("订单：" + order.orderSn + "获取订单信息失败  可能是小号过期了 \r\n");
                }
            }

            orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            this.dataGridView1.Rows.Clear();
            this.dataGridView1.DataSource = new BindingList<Order>(orderList.ToList());
        }

        private async void button4_Click_1(object sender, EventArgs e)
        {
            var tokens = pddTokenService.GetAllToken();
            foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
            {
                var order = item.DataBoundItem as Order;
                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.message.AppendText("小号没找到：" + order.uid + "\r\n");
                    continue;
                }
                //if (!string.IsNullOrWhiteSpace(order.orderState))
                //{
                //    if (order.orderState.Contains("待付款") || order.orderState.Contains("待收货") || order.orderState.Contains("待发货") || order.orderState.Contains("待分享") || order.orderState.Contains("待评价"))
                //    {

                //    }
                //    else
                //    {
                //        this.message.AppendText("订单不需要同步：" + order.uid + "\r\n");
                //    }
                //}
                try
                {
                    bool status = await PddApi.GetOrderStatus(order, token);
                    if (status)
                    {
                        await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                    }
                    else
                    {
                        this.message.AppendText("订单：" + order.orderSn + "获取订单信息失败  可能是小号过期了 \r\n");
                    }
                }
                catch
                {

                 
                }

               
            }
            this.dataGridView1.Refresh();
        }

    

        private async void button7_Click(object sender, EventArgs e)
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            OrderModel orderModel = new OrderModel();
            this.dataGridView1.Rows.Clear();
            string goodId = this.goods_id.Text.Trim();

            this.dataGridView1.DataSource = new BindingList<Order>(orderList.ToList());
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button8_Click(object sender, EventArgs e)
        {
            //var tokens = DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            //string url = "http://mobile.yangkeduo.com/proxy/api/api/aristotle/order_list?";
            //OrderModel orderModel = new OrderModel();

            //foreach (var item in tokens)
            //{

            //    var restclient = new RestClient(url);

            //    restclient.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64)";

            //    var request = new RestRequest(Method.POST);
            //    request.AddHeader("Content-Type", "application/x-www-form-urlencoded; Charset=UTF-8");
            //    request.AddHeader("Accept", "application/json, text/javascript, */*");
            //    request.AddHeader("Accept-Encoding", "gzip, deflate");
            //    request.AddHeader("AccessToken", item.PDDAccessToken);
            //    request.AddHeader("Host", "mobile.yangkeduo.com");
            //    request.AddHeader("Referer", url);
            //    request.AddCookie("PDDAccessToken", item.PDDAccessToken);

            //    orderModel.GetOrderType(this.order_type.Text);
            //    request.AddObject(orderModel);
            //    var response =  await restclient.ExecuteAsync(request);

            //    try
            //    {
            //        if (!string.IsNullOrWhiteSpace(response.Content))
            //        {
            //            GoogOrder googOrder = JsonHelper.DeserializeObject<GoogOrder>(response.Content);
            //            if (googOrder.orders == null || googOrder.orders.Count == 0)
            //            {
            //                continue;
            //            }
            //            foreach (var order in googOrder.orders)
            //            {
            //                if (order == null)
            //                {
            //                    continue;
            //                }
            //                if (order.order_goods.Count == 0)
            //                {
            //                    continue;
            //                }
            //                Order orderDao = new Order();
            //                GoodOrderViewModel goodOrderViewModel = new GoodOrderViewModel();
            //                //orderModel.MailId = order.mall.id;
            //                orderDao.uid = item.pdd_user_id;
            //                orderDao.token = item.PDDAccessToken;
            //                orderDao.mallName = order.mall.mall_name;
            //                orderDao.goodsId = order.order_goods[0].goods_id;
            //                orderDao.goodsName = order.order_goods[0].goods_name;
            //                orderDao.skuNumber = order.order_goods[0].sku_id;
            //                orderDao.buyTime = order.order_time.ToString();
            //                orderDao.orderSn = order.order_sn;
            //                orderDao.goodsMoney = order.order_amount.ToString();
            //                orderDao.orderState = order.order_status_prompt;

            //                var result = await DataBaseHelper.SqLiteDBCon.GetAsync<Order>(orderDao.orderSn);
            //                if (result != null)
            //                {
            //                    this.message.AppendText("更新本地订单信息：" + orderDao.orderSn + " \r\n");

            //                    await DataBaseHelper.SqLiteDBCon.UpdateAsync<Order>(orderDao);
            //                }
            //                else {
            //                    this.message.AppendText("新增订单到本地：" + orderDao.orderSn + " \r\n");

            //                    await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(orderDao);
            //                }

            //            }

            //        }
            //    }
            //    catch
            //    {
            //    }
            //}
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            if (!string.IsNullOrWhiteSpace(this.MallNameTextBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.mallName) && x.mallName.Contains(this.MallNameTextBox.Text));
            }

            if (!string.IsNullOrWhiteSpace(this.goods_id.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.goodsId) && x.goodsId.Contains(this.goods_id.Text));

            }

            if (!string.IsNullOrWhiteSpace(this.SearchText.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains(this.SearchText.Text));

            }

            this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = new BindingList<Order>(orderList.ToList());

            //if (comboBox2.Text == "根据店铺名")
            //{
            //    //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //    var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.mallName) && x.goodsId.Contains(this.SearchText.Text)).ToList();

            //    this.dataGridView1.DataSource = null;
            //    this.dataGridView1.DataSource = new BindingList<Order>(list);
            //}
            //else if (comboBox2.Text == "根据订单状态") 
            //{
            //    var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //    var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains(this.SearchText.Text)).ToList();

            //    this.dataGridView1.DataSource = null;
            //    this.dataGridView1.DataSource = new BindingList<Order>(list);
            //}
            //else if (comboBox2.Text == "根据产品ID")
            //{
            //    var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //    var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.goodsId) && x.goodsId.Contains(this.SearchText.Text)).ToList();

            //    this.dataGridView1.DataSource = null;
            //    this.dataGridView1.DataSource = new BindingList<Order>(list);
            //}


        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                dataGridView1.RowHeadersWidth - 4,
                e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        /// <summary>
        /// 收获
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button5_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定收货（自动查找已经签收的订单）？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                //点确定的代码
            }
            else
            {        //点取消的代码    
                return;
            }
            var tokens = pddTokenService.GetAllToken();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            foreach (DataGridViewRow item in this.dataGridView1.Rows)
            {
                var order = item.DataBoundItem as Order;
                if (!string.IsNullOrWhiteSpace(order.logisticsInfo) && order.logisticsInfo.Contains("已签收"))
                {
                    var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                    if (token == null)
                    {
                        this.message.AppendText("小号没找到：" + order.uid + "\r\n");
                        continue;
                    }
                    await GoodsReceived(order, token);
                }

            }
            //var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains("已签收")).ToList();
            //foreach (var order in list)
            //{
            //    var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            //    if (token == null)
            //    {
            //        this.message.AppendText("小号没找到：" + order.uid + "\r\n");
            //        continue;
            //    }
            //    await GoodsReceived(order, token);
            //}
        }

        /// <summary>
        /// 订单收货
        /// </summary>
        /// <param name="order"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private async Task GoodsReceived(Order order, PddToken token, string daili = null)
        {
            string url = "http://apiv4.yangkeduo.com/order/" + order.orderSn + "/received?pdduid=" + order.uid;
 
            var restclient = new RestClient(url);


            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 5.1; OPPO R9tm Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36";

            if (!string.IsNullOrWhiteSpace(daili))
            {
                restclient.Proxy = RestClientUtil.CreateWebProxy(daili);
            }

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("AccessToken", token.PDDAccessToken);
            request.AddHeader("Host", "apiv4.yangkeduo.com");
            request.AddHeader("Referer", url);
            var response = await restclient.ExecuteAsync(request);
            if (!string.IsNullOrWhiteSpace(response.Content) && (response.Content.Contains("已确认收货，正在前往评价...") || response.Content.Contains("已确认收货成功，请勿重复点击")))
            {
                order.orderState = "待评价";
                await DataBaseHelper.SqLiteDBCon.UpdateAsync<Order>(order);
                this.message.AppendText("订单：" + order.orderSn + "收获成功 \r\n");
            }
            else
            {
                this.message.AppendText("订单：" + order.orderSn + "收获失败 \r\n");
                this.message.AppendText(response.Content + "\r\n");
            }
        }

        private  void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.orderState) && x.orderState.Contains(this.comboBox1.Text)).ToList();

            //this.dataGridView1.DataSource = null;
            //this.dataGridView1.DataSource = new BindingList<Order>(list);
        }
        /// <summary>
        /// 一键好评
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button6_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定好评（自动查找待评价的订单）？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                //点确定的代码
            }
            else
            {        //点取消的代码    
                return;
            }
            var tokens = pddTokenService.GetAllToken(); //DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains("已签收")).ToList();

            foreach (DataGridViewRow item in this.dataGridView1.Rows)
            {
                var order = item.DataBoundItem as Order;
                if (!string.IsNullOrWhiteSpace(order.logisticsInfo) && order.logisticsInfo.Contains("已签收"))
                {
                    var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                    if (token == null)
                    {
                        this.message.AppendText("小号没找到：" + order.uid + "\r\n");
                        continue;
                    }

                    if (!order.orderState.Contains("待评价"))
                    {
                        continue;
                    }
                    await GoodsReview(order, token);
                }

            }

            //foreach (var order in list)
            //{
            //    var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            //    if (token == null)
            //    {
            //        this.message.AppendText("小号没找到：" + order.uid + "\r\n");
            //        continue;
            //    }

            //    if (!order.orderState.Contains("待评价"))
            //    {
            //        continue;
            //    }
            //    await GoodsReview(order, token);
            //}
        }

        private async Task GoodsReview(Order order, PddToken token, string comment = null, List<Images> imageUrlList = null, string daili = null)
        {
            Unrated unrated = new Unrated();
            unrated.goods_id = order.goodsId;
            unrated.order_sn = order.orderSn;
            unrated.anonymous = 0;
            unrated.timeline_sync_type = 1;
            unrated.comprehensive_dsr = 5;
            unrated.anti_content = "";
            if (comment != null)
            {
                unrated.comment = comment;
            }
            if (imageUrlList != null && imageUrlList.Count > 0)
            {
                unrated.pictures = imageUrlList;
            }

            string url = "http://mobile.yangkeduo.com/proxy/api/v2/order/goods/review?pdduid=" + order.uid;

            var restclient = new RestClient(url);

            if (!string.IsNullOrWhiteSpace(daili))
            {
                restclient.Proxy = RestClientUtil.CreateWebProxy(daili);
            }

            restclient.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1";

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("AccessToken", token.PDDAccessToken);
            request.AddHeader("Host", "mobile.yangkeduo.com");
            request.AddHeader("Origin", "http://mobile.yangkeduo.com");
            request.AddHeader("Referer", url);


            request.AddJsonBody(unrated);

            var response = await restclient.ExecuteAsync(request);
            if (!string.IsNullOrWhiteSpace(response.Content) && response.StatusCode == HttpStatusCode.OK)
            {
                order.orderState = "好评完成";
                await DataBaseHelper.SqLiteDBCon.UpdateAsync<Order>(order);
                this.message.AppendText("订单：" + order.orderSn + "五星好评成功 \r\n");
            }
            else
            {
                LogHelper.Logger.Debug("好评失败：" + response.Content);
                this.message.AppendText("订单：" + order.orderSn + "五星好评失败 \r\n");
            }
        }

        /// <summary>
        /// 单独收货
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button9_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定收货？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr != DialogResult.OK)
            {
                return;
            }

            var tokens = pddTokenService.GetAllToken();// DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            Order order = this.dataGridView1.CurrentRow.DataBoundItem as Order;
            if (order == null)
            {
                this.message.AppendText("请选中一行进行操作\r\n");
                return;
            }

            var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (token == null)
            {
                this.message.AppendText("小号没找到：" + order.uid + "\r\n");
                return;
            }

            string address = string.Empty;
            if (this.ProxyCheckBox.Checked)
            {
                address = this.ProxyIp.Text;
                if (string.IsNullOrWhiteSpace(address))
                {
                    MessageBox.Show("获取代理地址失败");
                    return;
                }
            }


            await GoodsReceived(order, token, address);

        }

        /// <summary>
        /// 选中的好评
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button3_Click_1(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定好评？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
            }
            else
            {        //点取消的代码    
                return;
            }
            var tokens = pddTokenService.GetAllToken();// DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains("已签收")).ToList();

            Order order = this.dataGridView1.CurrentRow.DataBoundItem as Order;
            if (order == null)
            {

                this.message.AppendText("请选中一行进行操作\r\n");
                return;
            }
            var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (token == null)
            {
                this.message.AppendText("小号没找到：" + order.uid + "\r\n");
                return;
            }

            if (!order.orderState.Contains("待评价"))
            {
                this.message.AppendText("待评价的才能好评：" + order.uid + "\r\n");
                return;
            }
            var imagesUrlList = new List<Images>();
            if (this.listView1.Items.Count > 0)
            {
                foreach (var item in this.listView1.Items)
                {
                    string base64 = null;
                    ListViewItem listViewItem = item as ListViewItem;
                    try
                    {
                        var resultBytes = new ThumbnailCreator().CreateThumbnailBytes(
                                              thumbnailSize: 900,
                                              imageStream: new FileStream(listViewItem.Name, FileMode.Open, FileAccess.Read),
                                              imageFormat: Format.Jpeg
                                          );
                        base64 = "data:image/jpg;base64," + Convert.ToBase64String(resultBytes);
                    }
                    catch (Exception)
                    {
                        base64 = "data:image/jpg;base64," + ImageUtil.ImgToBase64String(listViewItem.Name);
                    }
                    var sign = await PddApi.Signature(token, null, "review_image");
                    //var sign = await PddApi.UploadSignature(token);
                    if (string.IsNullOrWhiteSpace(sign))
                    {
                        this.message.AppendText("上传图片获取签名失败请重试" + order.uid + "\r\n");
                        return;
                    }
                    var imageObj = await PddApi.UploadImage(token, sign, base64, null);
                    if (imageObj == null)
                    {
                        this.message.AppendText("上传图片失败请重试" + order.uid + "\r\n");
                        return;
                    }
                    imagesUrlList.Add(imageObj);
                    this.message.AppendText("上传评论图片成功：" + listViewItem.Name + "\r\n");
                }

            }
            var selectedListViewItemCollection = this.listView1.SelectedItems;

            string address = string.Empty;
            if (this.ProxyCheckBox.Checked)
            {
                address = this.ProxyIp.Text;
                if (string.IsNullOrWhiteSpace(address))
                {
                    MessageBox.Show("获取代理地址失败");
                    return;
                }
            }

            await GoodsReview(order, token, this.comment.Text, imagesUrlList, address);
        }

        private void button10_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.jpg)|*.jpg";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                //FileStream fs = File.Open(file, FileMode.Open);
                //ImageUtil.CutForCustom(fs, "D://test//1.jpg", 900, 1200,70);



                bindListView(file);
            }

        }

        //下面是方法
        private void bindListView(string path)
        {
            imageList1.Images.Add(System.Drawing.Image.FromFile(path));
            listView1.Items.Add(path, System.IO.Path.GetFileName(path), 1);
            listView1.Items[0].ImageIndex = 1;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            var selectedListViewItemCollection = this.listView1.SelectedItems;
            foreach (var item in selectedListViewItemCollection)
            {
                ListViewItem listViewItem = item as ListViewItem;
                imageList1.Images.RemoveByKey(listViewItem.Name);
                listView1.Items.RemoveByKey(listViewItem.Name);
            }
        }

        private async void goods_id_SelectedIndexChanged(object sender, EventArgs e)
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.goodsId) && x.goodsId.Contains(this.goods_id.Text)).ToList();

            this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = new BindingList<Order>(list);
        }

      
    }


}
